package com.pug.pay.wechat.jsapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.pug.pay.wechat.jsapi.dto.PrepayRequest;
import com.pug.pay.wechat.jsapi.dto.PrepayResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author RenGaoshuai
 * @date 2023/6/25 15:53
 * @description jsapi支付业务
 */
public class JsapiWechatPayService {

    /**
     * 预下单
     *
     * @param request
     * @return
     */
    public PrepayResponse prepay(PrepayRequest request) {
        String requestPath = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        Map<String, String> header = new HashMap<>();
        header.put("accept", "application/json");
        header.put("content_type", "application/json");

        HttpResponse httpResponse = HttpUtil.createPost(requestPath)
                .addHeaders(header)
                .body(createRequestBody(request))
                .execute();

        return BeanUtil.copyProperties(httpResponse.body(), PrepayResponse.class);

    }

    private String createRequestBody(PrepayRequest request) {
        return Objects.nonNull(request) ? JSON.toJSONString(request) : null;
    }
}
